package Project;

import Hulppakket.*;

public class Sphere extends Surface{

	float radius;
	Point3f center;
	
	public Sphere()
	{
		radius = 1;
		center = new Point3f(0,0,0);
	}
	
	public Sphere(float nradius, Point3f ncenter, Color3f color)
	{
		radius = nradius;
		center = ncenter;
		this.setColor(color);
	}
	
	@Override
	boolean hit(Ray r, double t0, double t1, Hitrecord rec) {
		Point3f e = r.getOrigin();
		Vector3f d = r.getDirection();
		double A = Vector3f.Inp(d, d);
		double B = 2*Vector3f.Inp(d, Point3f.Min(e, center));
		double C =  (Vector3f.Inp(Point3f.Min(e, center),Point3f.Min(e, center))-Math.pow(getRadius(),2));
		double Discriminant = Math.pow(B, 2)-4*A*C;
		if (Discriminant <0) return false;
		if (Discriminant >0) {
			Vector3f eminc = Point3f.Min(e, center);
			double t2 = (-Vector3f.Inp(d, eminc)+Math.sqrt(Math.pow(Vector3f.Inp(d, eminc),2)-Vector3f.Inp(d, d)*(Vector3f.Inp(eminc, eminc)-Math.pow(this.getRadius(), 2))));
			double t3 = (-Vector3f.Inp(d, eminc)-Math.sqrt(Math.pow(Vector3f.Inp(d, eminc),2)-Vector3f.Inp(d, d)*(Vector3f.Inp(eminc, eminc)-Math.pow(this.getRadius(), 2))));
			t2 = t2/Vector3f.Inp(d, d);
			t3 = t3/Vector3f.Inp(d, d);
			double t4 = Math.min(t2, t3);
			double t5 = Math.max(t2, t3);
			if(t4 > t0 && t4 < t1) 
			{ 
				rec.t = (float) t4; 
			}
			else if(t5 > t0 && t5 < t1) 
			{ 
				rec.t = (float) t4; 
			}
			else 
			{ 
				return false;
			}
			rec.intersection = Point3f.Plus(e,d.multiply(rec.t));
			rec.normal = Point3f.Min(rec.intersection, center).divide(this.getRadius());
			rec.color = this.getColor();
			return true;
		}
		return false;
		
	}

	@Override
	Box boundingbox() {
		// TODO Auto-generated method stub
		return null;
	}

	public Point3f getCenter() {
		return center;
	}

	public void setCenter(Point3f center) {
		this.center = center;
	}

	public float getRadius() {
		return radius;
	}

	public void setRadius(float radius) {
		this.radius = radius;
	}

}
